'use strict'

const Service = require('egg').Service

class AuthService extends Service {
  async getAuthList(queryInfo) {
    // 如果没有 queryInfo.pagenum，说明是获取全部（这个不要做默认值修改，因为其他模块会调用该接口获得所有权限数据）
    if (!queryInfo.pageNum) {
      let resultAll = await this.app.mysql.query('SELECT * FROM c_auth ')

      return this.ctx.getRESTfulData(
        {
          total: resultAll.length,
          authList: resultAll,
        },
        '获取所有权限列表成功',
        200
      )
    }

    let resultAll = await this.app.mysql.query(
      `SELECT 
      *
      FROM c_auth 
      WHERE name like ?`,
      ['%' + queryInfo.keywords + '%']
    )

    let result = await this.app.mysql.query(
      `SELECT 
      *
      FROM c_auth 
      WHERE name like ?
      LIMIT ?,?`,
      [
        '%' + queryInfo.keywords + '%',
        parseInt(queryInfo.pageNum - 1) * queryInfo.pageSize,
        parseInt(queryInfo.pageSize),
      ]
    )

    return this.ctx.getRESTfulData(
      {
        total: resultAll.length,
        authList: result,
      },
      '获取筛选权限列表成功',
      200
    )
  }
  async getSingleAuth(options) {
    console.log(options)
    let result = await this.app.mysql.select('c_auth', {
      where: options,
    })
    console.log(result)
    return this.ctx.getRESTfulData(result, '获取单个权限成功', 200)
  }
  async createAuth(authInfo) {
    const singleResult = await this.getSingleAuth({
      departname: authInfo.departname,
    })

    if (singleResult.data.length > 0) {
      return this.ctx.getRESTfulData(null, '权限已存在', 401)
    }

    const result = await this.app.mysql.insert('c_auth', {
      ...authInfo,
    })

    if (result.affectedRows === 1) {
      const singleResult2 = await this.getSingleAuth({
        id: result.insertId,
      })

      return this.ctx.getRESTfulData(
        singleResult2.data[0],
        '新增权限列表成功',
        201
      )
    } else {
      return this.ctx.getRESTfulData(null, '新增权限列表失败', 401)
    }
  }
  async updateAuth(authInfo, id) {
    const singleResult = await this.getSingleAuth({
      departname: authInfo.departname,
    })

    if (singleResult.data.length > 0) {
      return this.ctx.getRESTfulData(null, '权限已存在', 401)
    }

    delete authInfo.id

    let result = await this.app.mysql.update('c_auth', {
      ...authInfo,
      id,
    })
    if (result.affectedRows === 1) {
      return {
        data: result,
        meta: {
          msg: '权限更新成功',
          status: 201,
        },
      }
    }
  }
  async deleteAuth(id) {
    let result = await this.app.mysql.delete('c_auth', {
      id,
    })
    if (result.affectedRows === 1) {
      return {
        data: result,
        meta: {
          msg: '权限删除成功',
          status: 200,
        },
      }
    }
  }
  async getAuthListByRoleName(options) {
    console.log(options)
    let roleRes = await this.app.mysql.select('c_role', {
      where: options,
    })

    const sqlStr = `SELECT * FROM c_auth WHERE id in ( ${roleRes[0].auths} )`

    let result = await this.app.mysql.query(sqlStr)

    /**
     * 将线性数据转换为树形数据
     * @param {Object} source 线性数据
     * @param {String}  id  属性名
     * @param {String} parentId 属性名
     * @param {String} children 属性名
     */
    function treeData(source, id, parentId, children) {
      let cloneData = JSON.parse(JSON.stringify(source))
      return cloneData.filter((father) => {
        let branchArr = cloneData.filter(
          (child) => father[id] == child[parentId]
        )
        branchArr.length > 0 ? (father[children] = branchArr) : ''
        return father[parentId] == 0 // 如果第一层不是parentId=0，请自行修改
      })
    }

    result = treeData(result, 'id', 'parent_id', 'children')

    return this.ctx.getRESTfulData(result, '获取单个权限成功', 200)
  }
}

module.exports = AuthService
